<template>
  <div class="school-manage">
    <el-card class="page-card">
      <template #header>
        <div class="card-header">
          <span class="title">校区管理</span>
          <div class="header-actions">
            <el-button type="primary" @click="showAddDialog">
              <el-icon><Plus /></el-icon>
              新增校区
            </el-button>
          </div>
        </div>
      </template>
      
      <!-- 搜索筛选 -->
      <div class="search-bar">
        <el-row :gutter="16">
          <el-col :span="6">
            <el-input
              v-model="searchForm.search"
              placeholder="搜索校区名称/代码"
              clearable
              @keyup.enter="handleSearch"
            >
              <template #prefix>
                <el-icon><Search /></el-icon>
              </template>
            </el-input>
          </el-col>
          <el-col :span="4">
            <el-button type="primary" @click="handleSearch">搜索</el-button>
            <el-button @click="handleReset">重置</el-button>
          </el-col>
        </el-row>
      </div>
      
      <!-- 校区表格 -->
      <el-table
        v-loading="loading"
        :data="schoolList"
        style="width: 100%"
      >
        <el-table-column prop="code" label="校区缩写" width="120" />
        <el-table-column prop="name" label="校区名称" width="200" />
        <el-table-column prop="principal" label="负责人" width="120" />
        <el-table-column prop="phone" label="联系电话" width="150" />
        <el-table-column prop="address" label="校区地址" show-overflow-tooltip />
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button size="small" @click="showEditDialog(row)">编辑</el-button>
            <el-button size="small" type="danger" @click="handleDelete(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <!-- 分页 -->
      <div class="pagination-wrapper">
        <el-pagination
          v-model:current-page="pagination.page"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
    
    <!-- 新增/编辑校区对话框 -->
    <el-dialog
      v-model="schoolDialogVisible"
      :title="isEdit ? '编辑校区' : '新增校区'"
      width="600px"
      @close="resetSchoolForm"
    >
      <el-form
        ref="schoolFormRef"
        :model="schoolForm"
        :rules="schoolRules"
        label-width="100px"
      >
        <el-form-item label="校区缩写" prop="code">
          <el-input v-model="schoolForm.code" :disabled="isEdit" placeholder="如：CD、XA" />
        </el-form-item>

        <el-form-item label="校区名称" prop="name">
          <el-input v-model="schoolForm.name" placeholder="如：成都校区" />
        </el-form-item>

        <el-form-item label="负责人" prop="principal">
          <el-input v-model="schoolForm.principal" placeholder="校区负责人姓名" />
        </el-form-item>

        <el-form-item label="联系电话" prop="phone">
          <el-input v-model="schoolForm.phone" placeholder="校区联系电话" />
        </el-form-item>

        <el-form-item label="校区地址" prop="address">
          <el-input v-model="schoolForm.address" type="textarea" rows="2" placeholder="校区详细地址" />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <el-button @click="schoolDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="submitting">
          {{ isEdit ? '更新' : '创建' }}
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Search } from '@element-plus/icons-vue'
import { schoolApi } from '@/api/students'

// 响应式数据
const loading = ref(false)
const schoolList = ref([])

// 搜索表单
const searchForm = reactive({
  search: ''
})

// 分页
const pagination = reactive({
  page: 1,
  pageSize: 20,
  total: 0
})

// 校区表单
const schoolDialogVisible = ref(false)
const isEdit = ref(false)
const submitting = ref(false)
const schoolFormRef = ref()

const schoolForm = reactive({
  id: null,
  code: '',
  name: '',
  principal: '',
  phone: '',
  address: ''
})

const schoolRules = {
  code: [{ required: true, message: '请输入校区缩写', trigger: 'blur' }],
  name: [{ required: true, message: '请输入校区名称', trigger: 'blur' }],
  principal: [{ required: true, message: '请输入负责人', trigger: 'blur' }],
  phone: [{ required: true, message: '请输入联系电话', trigger: 'blur' }],
  address: [{ required: true, message: '请输入校区地址', trigger: 'blur' }]
}

// API调用函数
const fetchSchoolList = async () => {
  loading.value = true
  try {
    const params = {
      page: pagination.page,
      page_size: pagination.pageSize,
      ...searchForm
    }
    
    const response = await schoolApi.getSchoolList(params)
    schoolList.value = response?.data.results || []
    pagination.total = response?.data.count || 0
  } catch (error) {
    console.error('获取校区列表失败:', error)
    ElMessage.error('获取校区列表失败')
    schoolList.value = []
    pagination.total = 0
  } finally {
    loading.value = false
  }
}

// 事件处理函数
const handleSearch = () => {
  pagination.page = 1
  fetchSchoolList()
}

const handleReset = () => {
  searchForm.search = ''
  handleSearch()
}

const handleSizeChange = (size: number) => {
  pagination.pageSize = size
  fetchSchoolList()
}

const handleCurrentChange = (page: number) => {
  pagination.page = page
  fetchSchoolList()
}

const showAddDialog = () => {
  isEdit.value = false
  schoolDialogVisible.value = true
  resetSchoolForm()
}

const showEditDialog = (row: any) => {
  isEdit.value = true
  schoolDialogVisible.value = true
  
  // 填充表单数据
  Object.keys(schoolForm).forEach(key => {
    (schoolForm as any)[key] = row[key] || ''
  })
}

const resetSchoolForm = () => {
  Object.keys(schoolForm).forEach(key => {
    (schoolForm as any)[key] = key === 'id' ? null : ''
  })
  schoolFormRef.value?.clearValidate()
}

const handleSubmit = async () => {
  try {
    await schoolFormRef.value.validate()
    submitting.value = true
    
    if (isEdit.value) {
      await schoolApi.updateSchool(schoolForm.id as unknown as number, schoolForm)
      ElMessage.success('校区信息更新成功')
    } else {
      await schoolApi.createSchool(schoolForm)
      ElMessage.success('校区创建成功')
    }
    
    schoolDialogVisible.value = false
    fetchSchoolList()
  } catch (error) {
    console.error('提交失败:', error)
    ElMessage.error(isEdit.value ? '更新失败' : '创建失败')
  } finally {
    submitting.value = false
  }
}

const handleDelete = async (row: any) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除校区 ${row.name}(${row.code}) 吗？删除后该校区下的所有专业、年级、班级数据也将被删除，此操作不可恢复！`,
      '删除确认',
      {
        confirmButtonText: '确定删除',
        cancelButtonText: '取消',
        type: 'warning',
        dangerouslyUseHTMLString: true
      }
    )

    const response = await schoolApi.deleteSchool(row.id)

    // 显示删除结果
    ElMessage({
      type: 'success',
      message: `校区 "${row.name}" 删除成功！`,
      duration: 3000
    })

    // 刷新列表
    await fetchSchoolList()

    console.log('校区删除成功:', response)
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除失败:', error)

      // 根据错误类型显示不同的错误信息
      let errorMessage = '删除失败'
      if ((error as any)?.response?.status === 400) {
        errorMessage = '该校区下还有关联数据，无法删除'
      } else if ((error as any)?.response?.status === 404) {
        errorMessage = '校区不存在或已被删除'
      } else if ((error as any)?.response?.status === 403) {
        errorMessage = '没有权限删除该校区'
      }

      ElMessage({
        type: 'error',
        message: errorMessage,
        duration: 5000
      })
    }
  }
}



// 生命周期
onMounted(() => {
  fetchSchoolList()
})
</script>

<style scoped>
.school-manage {
  padding: 20px;
}

.page-card {
  min-height: calc(100vh - 120px);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.title {
  font-size: 18px;
  font-weight: 600;
  color: var(--el-text-color-primary);
}

.header-actions {
  display: flex;
  gap: 12px;
}

.search-bar {
  margin-bottom: 20px;
  padding: 20px;
  background: var(--el-bg-color-page);
  border-radius: 8px;
}

.pagination-wrapper {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}

:deep(.el-table) {
  .el-table__header {
    background-color: var(--el-bg-color-page);
  }
  
  .el-table__row:hover {
    background-color: var(--el-fill-color-light);
  }
}

:deep(.el-dialog) {
  .el-dialog__header {
    border-bottom: 1px solid var(--el-border-color-light);
    padding-bottom: 15px;
  }
  
  .el-dialog__body {
    padding-top: 20px;
  }
}

@media (max-width: 768px) {
  .school-manage {
    padding: 10px;
  }
  
  .search-bar {
    padding: 15px;
  }
  
  .header-actions {
    flex-direction: column;
    gap: 8px;
  }
}
</style>
